package org.springblade.modules.admin.event;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springblade.common.mq.MqMessageService;
import org.springblade.modules.admin.dto.tlw.TlwRescuePlanChangeStateDTO;
import org.springblade.modules.admin.service.suger.IEstateTlwScreenService;
import org.springblade.modules.admin.vo.RescueOrderDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * @Author ysq
 * @Date 2025/08/12
 * @Description 监听器-给梯联网推送救援工单实时信息
 */
@Component
public class TlwRescueInfoEventListener {

	@Autowired
	private MqMessageService mqMessageService;

	@Autowired
	private IEstateTlwScreenService estateTlwScreenService;

	@Async
	@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
	public void handleRescueOrderCreated(TlwRescueInfoEvent event) {
			processRescueOrder(event.getRescueOrderDetail());
	}

	private void processRescueOrder(RescueOrderDetail rescueOrderDetail) {
		// 发送MQ消息
		mqMessageService.send(JSONObject.toJSONString(rescueOrderDetail, SerializerFeature.WRITE_MAP_NULL_FEATURES));

		// 同步工单状态到梯联网
		TlwRescuePlanChangeStateDTO changeStateParam = new TlwRescuePlanChangeStateDTO(
			rescueOrderDetail.getElevatorId(),
			rescueOrderDetail.getDeviceId(),
			rescueOrderDetail.getStatus(),
			rescueOrderDetail.getPlanId()
		);
		estateTlwScreenService.rescuePlanChangeState(changeStateParam);
	}
}
